package cn.jellybmedia.org.service.impl;

import cn.jellybmedia.basic.constant.BaseConstants;
import cn.jellybmedia.basic.exception.BusinessException;
import cn.jellybmedia.basic.utils.BaiduAuditUtils;
import cn.jellybmedia.org.domain.Employee;
import cn.jellybmedia.org.domain.Shop;
import cn.jellybmedia.org.domain.ShopAuditLog;
import cn.jellybmedia.org.mapper.EmployeeMapper;
import cn.jellybmedia.org.mapper.ShopAuditLogMapper;
import cn.jellybmedia.org.mapper.ShopMapper;
import cn.jellybmedia.org.service.IShopService;
import cn.jellybmedia.basic.service.impl.BaseServiceImpl;
import cn.jellybmedia.basic.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChuengXu
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    // 注入邮件对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;


    /**======================================================================================
    * @Title: settlement
    * @Description: 店铺入住实现类
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/1 16:39
    * @Parameters: [shop]
    * @Return void
    ======================================================================================*/
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        // 进行判断当前的参数是否为空,需要判断全部参数是否为空
            // 判断店铺的名称输入框是否为空
            if (StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getAdmin().getPhone())
                    || StringUtils.isEmpty(shop.getAdmin().getPhoneCode())){
                throw new RuntimeException("参数不能为空,请检查后重新输入!!!");
            }
        // 判断两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new RuntimeException("两次密码输入不一致,请检查后重新输入");
        }

        // 使用百度Ai判断店铺名称是否符合标准.
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new RuntimeException("您输入的店铺名称非法,请检查后重新输入");
        }

        // 使用百度Ai判断管理员名称是否符合标准.
        if (!BaiduAuditUtils.TextCensor(admin.getUsername())){
            throw new RuntimeException("您输入的管理员名称非法,请检查后重新输入");
        }


        // 使用百度ai判断对方logo是否符合标准

        // 校验手机号
        String phone = shop.getAdmin().getPhone(); // 手机号
        String phoneSettledCode = shop.getAdmin().getPhoneCode(); // 手机验证码

        // 判断两次手机号是否一致
        // 先获取上一次的手机号,需要用时间戳解出来
        String phoneCodeKey = BaseConstants.RegisterCodeConstants.BUSINESS_REGISTER_PREFIX + phone;
        Object phoneCodeValue = redisTemplate.opsForValue().get(phoneCodeKey);
        if (phoneCodeValue == null) {
            throw new BusinessException("手机验证码已过期,请重新获取验证码");
        }

        // 判断验证码是否正确
        String phoneCode = phoneCodeValue.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(phoneSettledCode)){
            throw new BusinessException("验证码不正确,请重新输入验证码");
        }

        // 校验邮箱
        // 获取参数
        String email = shop.getAdmin().getEmail();
        String emailCode = shop.getAdmin().getEmailCode();

        // 判断两次邮箱号是否一致
        // 先获取上一次的邮箱号,需要用时间戳解出来
        String emailCodeKey = BaseConstants.RegisterCodeConstants.BUSINESS_REGISTER_PREFIX + email;
        Object emailCodeValue = redisTemplate.opsForValue().get(emailCodeKey);
        if (emailCodeValue == null) {
            throw new BusinessException("邮箱验证码已过期,请重新获取验证码");
        }
        // 判断邮箱验证码是否正确
        String emailSettledCode = emailCodeValue.toString().split(":")[1];
        if (!emailSettledCode.equalsIgnoreCase(emailCode)){
            throw new BusinessException("验证码不正确,请重新输入验证码");
        }



        // 查询店铺是否存在,存在就进行返回,根据店铺名称查询
        Shop repeatShop = shopMapper.loadByName(shop.getName());
        if (repeatShop != null){
            throw new RuntimeException("店铺名重复,请重新输入");
        }


        Employee repeatEmp = employeeMapper.loadByUserName(admin.getUsername());
        // 查询管理员是否已经注册,并且还绑定了店铺.
        if (shop.getId() == null){
            if (repeatEmp != null && repeatEmp.getShopId() != null){
                throw new RuntimeException("此管理员已注册,并绑定了店铺,请重新输入管理员");
            }
        }

        // 管理员没进行注册,进行注册管理员
        if (repeatEmp == null){
            employeeMapper.save(admin);
            repeatEmp = admin;
        }

        // 将店铺和管理员进行互相绑定.因为员工表有店铺外键,店铺有员工的外键
        // 设置店铺管理员id
        shop.setAdminId(repeatEmp.getId());
        // 保存店铺,通过sql语句返回主键
        if (shop.getId() == null){
            shopMapper.save(shop);
        }else {
            shopMapper.update(shop);
        }
        // 设置员工表的管理店铺id
        repeatEmp.setShopId(shop.getId());
        // 修改员工表数据
        employeeMapper.update(repeatEmp);
    }


    /**======================================================================================
    * @Title: reject
    * @Description: 店铺驳回店铺申请方法
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/2 11:53
    * @Parameters: [shopAuditLog]
    * @Return void
    ======================================================================================*/
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // 修改店铺信息为未激活
        Integer shopId = shopAuditLog.getShopId();
        Long id = shopId.longValue();

        // 查找是那个店铺
        Shop shop = shopMapper.loadById(id);
        // 对店铺状态进行修改
        shop.setState(2);
        shopMapper.update(shop);
        // 写死ID,因为这是我我们平台自己的员工,所以员工不能有用店铺id
        shopAuditLog.setAuditId(327);

        // 调用日志保存方法,保存操作日志
        shopAuditLogMapper.save(shopAuditLog);

        // 发送邮件给各户
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("804854463@qq.com");
            helper.setSubject("店铺审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>店铺审核结果通知</h1>"+
                    "<h3>你好,你的店铺审核已完成,资料中存在违规信息,需要点击链接重新修改后再次提交</h3>" +
                    "失败原因:"+shopAuditLog.getNote() +
                    "<a href=http://localhost:8081/#/shopAgainRegister?shopId="+shopAuditLog.getShopId() +">修改链接</a>",true);
            // 5.设置收件人
            helper.setTo("804854463@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        }catch (RuntimeException e){
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }



    /**======================================================================================
    * @Title: pass
    * @Description: 店铺通过店铺申请方法
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/2 11:53
    * @Parameters: [shopAuditLog]
    * @Return void
    ======================================================================================*/
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // 修改店铺信息为待激活
        Integer shopId = shopAuditLog.getShopId();
        Long id = shopId.longValue();

        // 查找是那个店铺
        Shop shop = shopMapper.loadById(id);
        // 对店铺状态进行修改
        shop.setState(1);
        shopMapper.update(shop);


        // 写死ID,因为这是我我们平台自己的员工,所以员工不能有用店铺id
        shopAuditLog.setAuditId(327);

        // 调用日志保存方法,保存操作日志
        shopAuditLogMapper.save(shopAuditLog);

        // 发送邮件给各户
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("804854463@qq.com");
            helper.setSubject("店铺审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>店铺审核结果通知</h1>"+
                    "<h3>你好,你的店铺审核已完成,恭喜你审核通过,请点击下方链接激活,激活后方可正常使用</h3>"+

                    "<a href=http://localhost:8081/#/login?shopId="+shopAuditLog.getShopId()+">激活链接</a>",true);
            // 5.设置收件人
            helper.setTo("804854463@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        }catch (RuntimeException e){
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**======================================================================================
    * @Title: loadShopEcharts
    * @Description: 首页展示报表
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/3 12:32
    * @Parameters: []
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    ======================================================================================*/
    @Override
    public Map<String, Object> loadShopEcharts() {
        List<ShopVo>  shopVos= shopMapper.loadShopEcharts();


        ArrayList<String> states = new ArrayList<>();

        ArrayList<Integer> counts = new ArrayList<>();


        for (ShopVo shopVo: shopVos) {
            Integer state = shopVo.getStates();

            if (state == 0){
                states.add("待审核");
            };
            if (state == 1){
                states.add("已审核");
            };
            if (state == -1){
                states.add("驳回");
            };
            if (state == 2){
                states.add("待激活");
            }

            counts.add(shopVo.getCounts());

        }


        HashMap<String, Object> data = new HashMap<>();

        data.put("x",states);
        data.put("y",counts);

        System.out.println(data);

        return data;
    }

    /**======================================================================================
    * @Title: refuse
    * @Description: 拒绝拉黑对方
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/3 11:21
    * @Parameters: [shopAuditLog]
    * @Return void
    ======================================================================================*/
    @Override
    public void refuse(ShopAuditLog shopAuditLog) {

        Integer shopId = shopAuditLog.getShopId();
        Long id = shopId.longValue();

        // 查找是那个店铺
        Shop shop = shopMapper.loadById(id);
        // 对店铺状态进行修改
        shop.setState(-1);
        shopMapper.update(shop);

        // 添加操作记录
        shopAuditLogMapper.save(shopAuditLog);

        // 发送邮件给各户
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("804854463@qq.com");
            helper.setSubject("店铺审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>店铺审核结果通知</h1>"+
                    "<h3>你好,你的店铺审核已完成,因为你曾存在违规行为,已被永久封禁</h3>",true);
            // 5.设置收件人
            helper.setTo("804854463@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        }catch (RuntimeException e){
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }

    /**======================================================================================
    * @Title: getTransform
    * @Description: TODO
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/3 15:18
    * @Parameters: [id]
    * @Return cn.jellybmedia.org.domain.Shop
    ======================================================================================*/
    @Override
    public Shop getTransform(Long id) {

        System.out.println("service"+shopMapper.getTransform(id));
        return shopMapper.getTransform(id);
    }

    @Override
    public void addList(List<Shop> shops) {
        shopMapper.addList(shops);
    }
}
